<?php
if (!isset($___CHOOSE_DEPT_USET__TPL__INCLUDE)) {
    $___CHOOSE_DEPT_USET__TPL__INCLUDE = true;
    ?>
    <!-- 样式只加载一次 -->
    <style>
        .chooseDeptUserBox {
            min-height: 36px;
            border: solid #dddddd 1px;
            cursor: pointer;
            line-height: 36px;
            padding: 0 5px;
        }

        .chooseDeptUserBox .hint {
            color: #757575;
            padding: 0 5px;
        }

        .chooseDeptUserDialog {
            padding: 5px;
        }

        .chooseDeptUserDialog .left,
        .chooseDeptUserDialog .right {
            padding: 5px;
        }

        .chooseDeptUserDialog legend {
            font-size: 14px;
        }

        .chooseDeptUserDialog .layui-field-box {
            padding-top: 0;
        }

        .chooseDeptUserDialog .layui-tab.layui-tab-cdu {
            margin-top: 0;
        }

        .chooseDeptUserDialog .layui-tab-content {
            overflow: auto;
        }

        .chooseDeptUserDialog .selected .layui-elem-field .deptUser {
            overflow: auto;
        }

        .chooseDeptUserDialog .deptUserList input[type=checkbox] {
            display: initial;
            margin-right: 2px;
        }

        .chooseDeptUserDialog .deptUserList input[type=checkbox][disabled] {
            display: none;
        }

        .chooseDeptUserDialog .deptUserList li {
            line-height: 25px;
        }

        .chooseDeptUserDialog .deptUserList li .down {
            float: right;
        }

        .chooseDeptUserDialog .deptUserList li .close {
            float: right;
        }

        .chooseDeptUserDialog .deptUserList li .user-item {
            cursor: pointer;
            width: calc(100% - 60px);
            float: left;
            height: 26px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .chooseDeptUserDialog .deptUserList li i {
            margin-right: 2px;
        }

        .chooseDeptUserDialog .roleGroupList ul {
            margin-left: 20px;
        }

        .chooseDeptUserDialog .roleList li {
            line-height: 25px;
        }

        .chooseDeptUserDialog .roleGroupList li .role-item {
            cursor: pointer;
        }

        .chooseDeptUserDialog .roleGroupList li .role-item input[type='checkbox'],
        .chooseDeptUserDialog .roleGroupList li .role-item i {
            margin-right: 2px;
        }

        .chooseDeptUserDialog .selectedRoleList li .close {
            float: right;
        }

        .chooseDeptUserDialog .dynamicList li {
            line-height: 25px;
        }

        .chooseDeptUserDialog .dynamic li .dynamic-item {
            cursor: pointer;
        }

        .chooseDeptUserDialog .selectedDynamicList li .close {
            float: right;
        }

        .chooseDeptUserDialog .loadmore {
            text-align: center;
            margin-top: 5px;
        }

        .chooseDeptUserDialog .loadmore a {
            color: #38adff;
        }

        .chooseDeptUserDialog .deptPath {
            padding-bottom: 5px;
        }

        .chooseDeptUserDialog .deptPath .dp a {
            color: #38adff;
        }

        .chooseDeptUserDialog .deptPath .split {
            padding: 0 5px;
        }
    </style>

    <!-- 全局js只加载一次 -->
    <script>
        g.cdu = {
            /**
             * 获取选择结果
             *
             * @param id
             * @returns {jQuery}
             */
            get: function (id) {
                return $("#dept_user_val_" + id).val();
            },
            /**
             * 设置选择结果
             *
             * @param id
             * @param items
             */
            set: function (id, items) {
                if (typeof items == 'string') {
                    items = eval("(" + items + ")");
                }
                var $boxElem = $("#chooseDeptUserBox_" + id);
                $boxElem.data("items", items);
                var fieldName = $boxElem.attr("data-name");

                var elemsHtml = [];
                for (var i = 0; i < items.length; i++) {
                    elemsHtml.push("<span class='item'>" + items[i].name + "</span>");
                }

                var $selectedList = $(".selectedList", $boxElem);
                $selectedList.html("");
                $selectedList.append(elemsHtml.join(", "));
                $selectedList.append("<input type='hidden' id='dept_user_val_" + id + "' name='" + fieldName + "' value='" + JSON.stringify(items) + "'/>");
                if (items.length == 0) {
                    $(".hint", $boxElem).show();
                } else {
                    $(".hint", $boxElem).hide();
                }
            },
            /**
             * 设置选择发生改变时的触发函数
             *
             * @param id
             * @param callback
             */
            onChange: function (id, callback) {
                var $boxElem = $("#chooseDeptUserBox_" + id);
                $boxElem.data("callback", callback);
            },
            /**
             * 显示选择对话框
             *
             * @param id
             */
            show: function (id) {
                var $boxElem = $("#chooseDeptUserBox_" + id);
                $boxElem.click();
            }
        }
        ;
    </script>

    <?php
}
?>
<?php
$entTitle = isset($enterprise) ? $enterprise['title'] : "";
?>
<div class="chooseDeptUserBox" id="chooseDeptUserBox_<?php echo $__cdu_id; ?>"
     data-dept="<?php echo $__cdu_dept; ?>"
     data-user="<?php echo $__cdu_user; ?>"
     data-role="<?php echo $__cdu_role; ?>"
     data-dynamic="<?php echo $__cdu_dynamic; ?>"
     data-rootDeptId="<?php echo $__cdu_rootDept; ?>"
     data-name="<?php echo $__cdu_name; ?>"
     data-multi="<?php echo $__cdu_multi; ?>"
>
    <span class="hint"><?php echo $__cdu_hint; ?></span>
    <span class="selectedList"></span>
</div>

<div class="chooseDeptUserDialog" id="chooseDeptUserDialog_<?php echo $__cdu_id; ?>" style="display: none;">
    <div class="layui-row">
        <div class="layui-col-xs6 left aviable">
            <fieldset class="layui-elem-field">
                <legend>选择：</legend>
                <div class="layui-field-box">
                    <div class="layui-tab layui-tab-cdu layui-tab-brief" lay-filter="cdu_tab_<?php echo $__cdu_id; ?>">
                        <ul class="layui-tab-title">
                            <li lay-id="deptUser" style="display: none">通讯录</li>
                            <li lay-id="role" style="display: none">角色</li>
                            <li lay-id="dynamic" style="display: none">动态人员</li>
                        </ul>
                        <div class="layui-tab-content">
                            <div class="layui-tab-item">
                                <!-- 当前所属通讯录路径 -->
                                <div class="deptPath"></div>
                                <div class="deptUser">
                                    <!-- 部门列表 -->
                                    <div class="dept">
                                        <ul class="deptUserList aviableDeptUserList">
                                        </ul>
                                    </div>
                                    <!-- 用户列表 -->
                                    <div class="user">
                                        <ul class="deptUserList aviableDeptUserList">
                                        </ul>
                                        <input type="hidden" class="userOffset" value="0"/>
                                        <div class="loadmore">
                                            <a href="javascript:;">加载更多&gt;&gt;</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-tab-item">
                                <div class="role">
                                    <ul class="roleGroupList aviableRoleGroupList">
                                    </ul>
                                    <input type="hidden" class="roleOffset" value="0"/>
                                    <div class="loadmore">
                                        <a href="javascript:;">加载更多&gt;&gt;</a>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-tab-item">
                                <div class="dynamic">
                                    <ul class="dynamicList aviableDynamicList">
                                        <li>
                                            <span class="dynamic-item">
                                                <input type="checkbox" value="initiator"/>
                                                <i class="layui-icon-ext layui-icon-ext-dynamic-user"></i>
                                                <span>发起人</span>
                                            </span>
                                        </li>
                                        <li>
                                            <span class="dynamic-item">
                                                <input type="checkbox" value="initiator-director-1"/>
                                                <i class="layui-icon-ext layui-icon-ext-dynamic-user"></i>
                                                <span>发起人上级主管</span>
                                            </span>
                                        </li>
                                        <li>
                                            <span class="dynamic-item">
                                                <input type="checkbox" value="initiator-director-2"/>
                                                <i class="layui-icon-ext layui-icon-ext-dynamic-user"></i>
                                                <span>发起人上上级主管</span>
                                            </span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </fieldset>
        </div>
        <div class="layui-col-xs6 right selected">
            <fieldset class="layui-elem-field">
                <legend>已选：</legend>
                <div class="layui-field-box">
                    <div class="deptUser">
                        <!-- 动态人员列表 -->
                        <div class="dynamic">
                            <ul class="dynamicList selectedDynamicList">
                            </ul>
                        </div>
                        <!-- 角色列表 -->
                        <div class="role">
                            <ul class="roleList selectedRoleList">
                            </ul>
                        </div>
                        <!-- 部门列表 -->
                        <div class="dept">
                            <ul class="deptUserList selectedDeptUserList">
                            </ul>
                        </div>
                        <!-- 用户列表 -->
                        <div class="user">
                            <ul class="deptUserList selectedDeptUserList">
                            </ul>
                        </div>
                    </div>
                </div>
            </fieldset>
        </div>
    </div>
</div>

<script>
    layui.use('element', function () {
        var element = layui.element;
        $(document).ready(function () {
            // 首先将弹出框对应的div移动到最外层，否则有的时候会弹不出来
            document.body.appendChild(document.getElementById("chooseDeptUserDialog_<?php echo $__cdu_id; ?>"));

            var deptPath = [];
            var cache = {depts: {}, users: {}, roles: {}};
            var $boxElem = $("#chooseDeptUserBox_<?php echo $__cdu_id; ?>");
            var $dlgElem = $("#chooseDeptUserDialog_<?php echo $__cdu_id; ?>");
            var deptEnable = $boxElem.attr("data-dept") == 'true';
            var userEnable = $boxElem.attr("data-user") == 'true';
            var roleEnable = $boxElem.attr("data-role") == 'true';
            var dynamicEnable = $boxElem.attr("data-dynamic") == 'true';
            var fieldName = $boxElem.attr("data-name");
            var multi = $boxElem.attr("data-multi") != 'false';
            var rootDeptId = $boxElem.attr("data-rootDeptId");
            if (!rootDeptId) {
                rootDeptId = 1;
            }
            var initValue = [];
            try {
                initValue = eval('(<?php echo is_array($__cdu_value) ? json_encode($__cdu_value) : $__cdu_value; ?>)');
                g.cdu.set("<?php echo $__cdu_id; ?>", initValue);
            } catch (e) {
                console.error(e);
            }

            $boxElem.click(function () {
                showChooseDialog("<?php echo $__cdu_id; ?>");
            });

            // tab选项
            var firstShowTabId = false;
            $(".layui-tab-title>li", $dlgElem).hide();
            if (deptEnable || userEnable) {
                $(".layui-tab-title>li[lay-id='deptUser']", $dlgElem).show();
                if (!firstShowTabId) firstShowTabId = 'deptUser';
            }
            if (roleEnable) {
                $(".layui-tab-title>li[lay-id='role']", $dlgElem).show();
                if (!firstShowTabId) firstShowTabId = 'role';
            }
            if (dynamicEnable) {
                $(".layui-tab-title>li[lay-id='dynamic']", $dlgElem).show();
                if (!firstShowTabId) firstShowTabId = 'dynamic';
            }
            console.log("firstShowTabId=" + firstShowTabId);
            element.tabChange("cdu_tab_<?php echo $__cdu_id; ?>", firstShowTabId);

            // 可选人员及部门列表中，复选框勾选和取消选中触发
            $("ul.aviableDeptUserList", $dlgElem).delegate("li input[type='checkbox']", "click", function () {
                var type = $(this).attr("data-idType");
                var deptUserId = this.value;
                var deptUserName = $(this).attr("data-deptUserName");
                if (this.checked) {
                    // 选中
                    if (isDeptUserItemSelected(deptUserId, type)) {
                        return;
                    } else {
                        handleMultiSelected();
                        $("." + type + " ul.selectedDeptUserList", $dlgElem).append(
                            generateDeptUserItemSelectedHtml(deptUserId, deptUserName, type)
                        );
                    }
                } else {
                    // 取消选中，从选中列表中删除
                    removeSelectedDeptUserItem(deptUserId, type);
                }
            });
            $("ul.aviableDeptUserList", $dlgElem).delegate("li .user-item", "click", function (e) {
                if ($("input[type='checkbox']", this)[0] == e.target) {
                    return;
                }
                $("input[type='checkbox']", this).click();
            });
            // 可选人员及部门列表加载更多人员
            $(".user .loadmore a", $dlgElem).click(function () {
                var deptId = $(".deptPath", $dlgElem).attr("data-currentDeptId");
                renderNextAvaliableUserList(deptId);
            });
            // 可选人员及部门列表下级部门
            $(".dept ul.aviableDeptUserList", $dlgElem).delegate(".down", "click", function () {
                $dataElem = $("input[type='checkbox'][data-idtype='dept']", $(this).parent());
                var deptId = $dataElem.val();
                var deptName = $dataElem.attr("data-deptUserName");
                deptPath.push({
                    'id': deptId,
                    'name': deptName
                });
                reRenderDeptUserList(deptId);
            });
            // 人员及部门通讯录路径点击
            $(".deptPath", $dlgElem).delegate(".dp a", "click", function () {
                var deptId = $(this).attr("data-deptId");
                if (deptId == rootDeptId) {
                    deptPath = [];
                } else {
                    var newDeptPath = [];
                    for (var i = 0; i < deptPath.length; i++) {
                        newDeptPath.push(deptPath[i]);
                        if (deptPath[i].id == deptId) {
                            break;
                        }
                    }
                    deptPath = newDeptPath;
                }
                reRenderDeptUserList(deptId);
            });
            // 已选择人员及部门列表中移除按钮
            $("ul.selectedDeptUserList", $dlgElem).delegate("a.close", "click", function () {
                var $dataElem = $("input[type='hidden']", $(this).parent());
                var deptUserId = $dataElem.val();
                var type = $dataElem.attr("data-idType");
                removeSelectedDeptUserItem(deptUserId, type);
            });
            // 可选角色列表加载更多角色
            $(".role .loadmore a", $dlgElem).click(function () {
                reRenderNextRoleList();
            });
            // 可选角色列表中，复选框勾选和取消选中触发
            $(".role .aviableRoleGroupList", $dlgElem).delegate("li .role-item input[type='checkbox']", "click", function () {
                var roleName = $(this).attr("data-roleName");
                var roleId = this.value;
                if (this.checked) {
                    // 选中
                    if (isRoleItemSelected(roleId)) {
                        return;
                    } else {
                        handleMultiSelected();
                        $("ul.selectedRoleList", $dlgElem).append(
                            generateRoleSelectedHtml(roleId, roleName)
                        );
                    }
                } else {
                    // 取消选中，从选中列表中删除
                    removeSelectedRoleItem(roleId);
                }
            });
            $(".role .aviableRoleGroupList", $dlgElem).delegate("li .role-item", "click", function (e) {
                if ($("input[type='checkbox']", this)[0] == e.target) {
                    return;
                }
                $("input[type='checkbox']", this).click();
            });
            // 已选择角色列表中移除按钮
            $("ul.selectedRoleList", $dlgElem).delegate("a.close", "click", function () {
                $dataElem = $("input[type='hidden']", $(this).parent());
                var roleId = $dataElem.val();
                removeSelectedRoleItem(roleId);
            });
            // 可选动态人员列表中，复选框勾选和取消选中触发
            $(".dynamic .aviableDynamicList", $dlgElem).delegate("li .dynamic-item input[type='checkbox']", "click", function () {
                var dynamicName = $(this).parent().find(">span").text();
                var dynamicId = this.value;
                if (this.checked) {
                    // 选中
                    if (isDynamicItemSelected(dynamicId)) {
                        return;
                    } else {
                        handleMultiSelected();
                        $("ul.selectedDynamicList", $dlgElem).append(
                            generateDynamicSelectedHtml(dynamicId, dynamicName)
                        );
                    }
                } else {
                    // 取消选中，从选中列表中删除
                    removeSelectedDynamicItem(dynamicId);
                }
            });
            $(".dynamic .aviableDynamicList", $dlgElem).delegate("li .dynamic-item", "click", function (e) {
                if ($("input[type='checkbox']", this)[0] == e.target) {
                    return;
                }
                $("input[type='checkbox']", this).click();
            });
            // 已选择动态人员列表中移除按钮
            $("ul.selectedDynamicList", $dlgElem).delegate("a.close", "click", function () {
                $dataElem = $("input[type='hidden']", $(this).parent());
                var dynamicId = $dataElem.val();
                removeSelectedDynamicItem(dynamicId);
            });

            // 预加载
            if (!window.__CDU_DEPT_USER_PRELOAD) {
                window.__CDU_DEPT_USER_PRELOAD = {};
            }
            if (!window.__CDU_DEPT_USER_PRELOAD['dept_' + rootDeptId]) {
                window.__CDU_DEPT_USER_PRELOAD['dept_' + rootDeptId] = true;
                reRenderDeptUserList(rootDeptId);
            }
            if (!window.__CDU_ROLE_PRELOAD) {
                window.__CDU_ROLE_PRELOAD = true;
                reRenderRoleList();
            }

            /**
             * 处理多选
             */
            function handleMultiSelected() {
                if (!multi) {
                    $(".right.selected .close", $dlgElem).click();
                }
            }

            /**
             * 显示选取部门及人员的对话框
             */
            function showChooseDialog(cduId) {
                var titles = [];
                if (deptEnable) {
                    titles.push("部门");
                }
                if (userEnable) {
                    titles.push("人员");
                }
                if (roleEnable) {
                    titles.push("角色");
                }
                if (dynamicEnable) {
                    titles.push("动态人员");
                }
                if (titles.length == 0) {
                    layer.alert("配置错误");
                    return;
                }
                var title = "请选择" + titles.join("、");

                // 初始化当前选择
                $dlgElem.find("ul.selectedDeptUserList").html("");
                $dlgElem.find("ul.selectedRoleList").html("");
                $dlgElem.find("ul.selectedDynamicList").html("");
                var $boxElem = $("#chooseDeptUserBox_" + cduId);
                var initItems = $boxElem.data("items");
                console.log(initItems);
                if (initItems && initItems.length) {
                    for (var i = 0; i < initItems.length; i++) {
                        var item = initItems[i];
                        if (item.type == 'role') {
                            $dlgElem.find("ul.selectedRoleList").append(
                                generateRoleSelectedHtml(item.id, item.name)
                            );
                        } else if (item.type == 'dynamic') {
                            $(".dynamic .aviableDynamicList li input[value='" + item.id + "']", $dlgElem).attr("checked", true);
                            $dlgElem.find("ul.selectedDynamicList").append(
                                generateDynamicSelectedHtml(item.id, item.name)
                            );
                        } else {
                            $dlgElem.find("." + item.type + " ul.selectedDeptUserList").append(
                                generateDeptUserItemSelectedHtml(item.id, item.name, item.type)
                            );
                        }
                    }
                }

                var height = (window.frameElement ? $(window.frameElement).height() : $(window).height()) - 50;
                if (height > 600) {
                    height = 600;
                }

                layer.open({
                    type: 1
                    , title: title
                    , closeBtn: false
                    , offset: '50px'
                    , area: ['720px', height + 'px']
                    , shade: 0.8
                    , shadeClose: true
                    , id: 'LAY_chooseDeptUser_<?php echo $__cdu_id; ?>' //设定一个id，防止重复弹出
                    , btn: ['确定', '取消']
                    , btnAlign: 'c'
                    , moveType: 1 //拖拽模式，0或者1
                    , zIndex: 999999999
                    , content: $("#chooseDeptUserDialog_<?php echo $__cdu_id; ?>")
                    , success: function (layero) {
                        var height = $("#LAY_chooseDeptUser_<?php echo $__cdu_id; ?>").height();
                        $(".aviable .layui-elem-field").css("height", height - 15);
                        $(".selected .layui-elem-field").css("height", height - 15);
                        $(".aviable .layui-elem-field .layui-tab-content").css("height", height - 100);
                        $(".selected .layui-elem-field .deptUser").css("height", height - 40);
                    }
                    , yes: function (index, layero) {
                        //确定按钮的回调
                        var selectedItems = [];
                        $("ul.selectedDynamicList li input[type='hidden']", $dlgElem).each(function () {
                            var dynamicName = $(this).attr("data-dynamicName");
                            var dynamicId = $(this).val();
                            selectedItems.push({
                                'id': dynamicId,
                                'name': dynamicName,
                                'type': "dynamic"
                            });
                        });
                        $("ul.selectedRoleList li input[type='hidden']", $dlgElem).each(function () {
                            var roleName = $(this).attr("data-roleName");
                            var roleId = $(this).val();
                            selectedItems.push({
                                'id': roleId,
                                'name': roleName,
                                'type': "role"
                            });
                        });
                        $("ul.selectedDeptUserList li input[type='hidden']", $dlgElem).each(function () {
                            var deptUserName = $(this).attr("data-deptUserName");
                            var type = $(this).attr("data-idType");
                            var deptUserId = $(this).val();
                            selectedItems.push({
                                'id': deptUserId,
                                'name': deptUserName,
                                'type': type
                            });
                        });
                        g.cdu.set("<?php echo $__cdu_id; ?>", selectedItems);

                        // 回调
                        var callback = $boxElem.data("callback");
                        callback && (typeof callback == 'function') && callback(selectedItems);

                        layer.close(index);
                        return true;
                    }
                });

                //显示部门及人员列表
                deptPath = [];
                reRenderDeptUserList(rootDeptId);
                if (roleEnable) {
                    reRenderRoleList();
                }
            }

            /**
             * 渲染通讯录路径
             */
            function renderDeptPath() {
                var rootTitle = '<?php echo $entTitle;?>';
                if (!rootTitle) {
                    rootTitle = "通讯录";
                }
                $deptPath = $(".deptPath", $dlgElem);
                //清空
                $deptPath.html("");
                if (deptPath.length == 0) {
                    $deptPath.append("<span class='dp'>" + rootTitle + "</span>");
                } else {
                    $deptPath.append("<span class='dp'><a href='javascript:;' data-deptId='" + rootDeptId + "'>" + rootTitle + "</a></span>");
                    for (var i = 0; i < deptPath.length - 1; i++) {
                        var dp = deptPath[i];
                        $deptPath.append("<span class='split'>&gt;</span>");
                        $deptPath.append("<span class='dp'><a href='javascript:;' data-deptId='" + dp.id + "'>" + dp.name + "</a></span>");
                    }
                    var dp = deptPath[deptPath.length - 1];
                    $deptPath.append("<span class='split'>&gt;</span>");
                    $deptPath.append("<span class='dp'>" + dp.name + "</span>");
                }
                var currentDeptId = rootDeptId;
                if (deptPath.length > 0) {
                    currentDeptId = deptPath[deptPath.length - 1].id;
                }
                $(".deptPath", $dlgElem).attr("data-currentDeptId", currentDeptId);
            }

            /**
             * 重新渲染部门及用户列表
             * @param deptId
             */
            function reRenderDeptUserList(deptId) {
                //清空可供选择的区域
                $("ul.aviableDeptUserList", $dlgElem).html("");
                $(".userOffset", $dlgElem).val("0");
                $(".user .loadmore a", $dlgElem).hide();
                $(".current ul li.dynamic", $dlgElem).remove();

                renderAvaliableDeptList(deptId, deptEnable);
                if (userEnable) {
                    renderNextAvaliableUserList(deptId);
                }

                renderDeptPath();
            }

            /**
             * 渲染可供选择的部门列表
             */
            function renderAvaliableDeptList(deptId, canCheck) {
                getDeptList(deptId, function (depts) {
                    console.dir(depts);
                    for (var i = 0; i < depts.length; i++) {
                        var dept = depts[i];
                        if (isDeptUserItemAvaliable(dept.id, "dept")) {
                            continue;
                        }
                        $(".dept ul.aviableDeptUserList", $dlgElem).append(
                            generateDeptUserItemAvaliableHtml(dept.id, dept.title, "dept", canCheck)
                        );
                    }
                });
            }

            /**
             * 渲染可供选择的用户列表
             */
            function renderNextAvaliableUserList(deptId) {
                $(".user .loadmore a", $dlgElem).show().text("加载中...");
                var offset = parseInt($(".userOffset", $dlgElem).val());
                getUserList(deptId, offset, function (usersResult) {
                    console.dir(usersResult);
                    if (usersResult.hasMore) {
                        $(".user .loadmore a", $dlgElem).text("加载更多>>");
                        $(".user .loadmore a", $dlgElem).show();
                    } else {
                        $(".user .loadmore a", $dlgElem).hide();
                    }
                    for (var i = 0; i < usersResult.userlist.length; i++) {
                        var user = usersResult.userlist[i];
                        if (isDeptUserItemAvaliable(user.id, "user")) {
                            continue;
                        }
                        $(".user ul.aviableDeptUserList", $dlgElem).append(
                            generateDeptUserItemAvaliableHtml(user.id, user.showname, "user")
                        );
                    }
                    $(".userOffset", $dlgElem).val(offset + usersResult.userlist.length);
                });
            }

            /**
             * 当前部门或者用户是否可供选择
             */
            function isDeptUserItemAvaliable(deptOrUserId, type) {
                return $("." + type + " ul.aviableDeptUserList li input[data-idType='" + type + "'][value='" + deptOrUserId + "']", $dlgElem).length > 0;
            }

            /**
             * 当前部门或者用户是否被选中
             */
            function isDeptUserItemSelected(deptOrUserId, type) {
                return $("." + type + " ul.selectedDeptUserList li input[data-idType='" + type + "'][value='" + deptOrUserId + "']", $dlgElem).length > 0;
            }

            /**
             * 将部门或者用户取消选中
             */
            function removeSelectedDeptUserItem(deptOrUserId, type) {
                $("." + type + " ul.selectedDeptUserList li input[data-idType='" + type + "'][value='" + deptOrUserId + "']", $dlgElem).parent().remove();
                if (isDeptUserItemAvaliable(deptOrUserId, type)) {
                    $("." + type + " ul.aviableDeptUserList li input[data-idType='" + type + "'][value='" + deptOrUserId + "']", $dlgElem).attr("checked", false);
                }
            }

            /**
             * 生成部门或者用户可供选择的元素
             */
            function generateDeptUserItemAvaliableHtml(deptOrUserId, deptOrUserName, type, canCheck) {
                var checked = isDeptUserItemSelected(deptOrUserId, type) ? "checked" : "";
                var disbaled = canCheck == false ? "disabled" : "";
                var html = "";
                html += "<div class='user-item' title='" + deptOrUserName + "'><input type='checkbox' value='" + deptOrUserId + "' data-deptUserName='" + deptOrUserName + "' data-idType='" + type + "' " + checked + " " + disbaled + "/>";
                if (type == 'dept') {
                    html += '<i class="layui-icon-ext layui-icon-ext-dept"></i>';
                } else {
                    html += '<i class="layui-icon-ext layui-icon-ext-user"></i>';
                }
                html += "<span>" + deptOrUserName + "</span></div>"
                if (type == 'dept') {
                    html += "<a href='javascript:;' class='down'><i class='layui-icon'>&#xe601;</i>下级</a>";
                }
                return "<li>" + html + "</li>";
            }

            /**
             * 生成部门或者用户选中后的元素
             */
            function generateDeptUserItemSelectedHtml(deptOrUserId, deptOrUserName, type) {
                var html = "";
                html += "<input type='hidden' value='" + deptOrUserId + "' data-deptUserName='" + deptOrUserName + "' data-idType='" + type + "'/>";
                if (type == 'dept') {
                    html += '<i class="layui-icon-ext layui-icon-ext-dept"></i>';
                } else {
                    html += '<i class="layui-icon-ext layui-icon-ext-user"></i>';
                }
                html += "<span>" + deptOrUserName + "</span>"
                html += "<a href='javascript:;' class='close'>" +
                    "<i class='layui-icon layui-icon-close'></i>" +
                    "</a>";
                return "<li>" + html + "</li>";
            }

            /**
             * 渲染角色列表
             */
            function reRenderRoleList() {
                //清空可供选择的区域
                $(".role ul.aviableRoleGroupList", $dlgElem).html("");
                $(".roleOffset", $dlgElem).val("0");
                $(".role .loadmore a", $dlgElem).hide();

                reRenderNextRoleList();
            }

            /**
             * 渲染角色下一页列表
             */
            function reRenderNextRoleList() {
                $(".role .loadmore a", $dlgElem).show().text("加载中...");
                var offset = parseInt($(".roleOffset", $dlgElem).val());
                getRoleList(offset, function (roleResult) {
                    console.log(roleResult);
                    if (roleResult.hasMore == 'true' || roleResult.hasMore === true) {
                        $(".role .loadmore a", $dlgElem).text("加载更多>>");
                        $(".role .loadmore a", $dlgElem).show();
                    } else {
                        $(".role .loadmore a", $dlgElem).hide();
                    }
                    for (var i = 0; i < roleResult.list.length; i++) {
                        var group = roleResult.list[i];
                        var html = generateRoleGroupAvaliableHtml(group);
                        $(".aviableRoleGroupList").append(html);
                    }
                    $(".roleOffset", $dlgElem).val(offset + roleResult.list.length);

                });
            }

            /**
             * 生成角色组元素
             */
            function generateRoleGroupAvaliableHtml(roleGroup) {
                var html = "<li>";
                html += "<div class='title'>" + roleGroup.group_name + "</div>";
                html += "<ul class='roleList availableRoleList'>";
                for (var i = 0; i < roleGroup.roles.length; i++) {
                    var role = roleGroup.roles[i];
                    html += generateRoleAvaliableHtml(role);
                }
                html += "</ul>";
                html += "</li>";
                return html;
            }

            /**
             * 生成角色元素内容
             */
            function generateRoleAvaliableHtml(role) {
                var html = "";
                var checked = isRoleItemSelected(role.id) ? "checked" : "";
                html += "<span class='role-item'>";
                html += "<input type='checkbox' value='" + role.id + "' data-roleName='" + role.role_name + "' " + checked + " />";
                html += '<i class="layui-icon-ext layui-icon-ext-role"></i>';
                html += "<span>" + role.role_name + "</span>";
                html += "</span>";
                return "<li>" + html + "</li>";
            }

            /**
             * 生成角色选中元素
             */
            function generateRoleSelectedHtml(roleId, roleName) {
                var html = "";
                html += "<input type='hidden' value='" + roleId + "' data-roleName='" + roleName + "'/>";
                html += '<i class="layui-icon-ext layui-icon-ext-role"></i>';
                html += "<span>" + roleName + "</span>";
                html += "<a href='javascript:;' class='close'>" +
                    "<i class='layui-icon layui-icon-close'></i>" +
                    "</a>";
                return "<li>" + html + "</li>";
            }

            /**
             * 移除角色选中
             */
            function removeSelectedRoleItem(roleId) {
                $("ul.selectedRoleList li input[value='" + roleId + "']", $dlgElem).parent().remove();
                if (isRoleItemAvaliable(roleId)) {
                    $(".role .aviableRoleGroupList li input[value='" + roleId + "']", $dlgElem).attr("checked", false);
                }
            }

            /**
             * 判断角色是否被选中
             */
            function isRoleItemSelected(roleId) {
                return $("ul.selectedRoleList li input[value='" + roleId + "']", $dlgElem).length > 0;
            }

            /**
             * 判断角色是否存在可选列表中
             */
            function isRoleItemAvaliable(roleId) {
                return $(".role .aviableRoleGroupList li input[value='" + roleId + "']", $dlgElem).length > 0;
            }

            /**
             * 判断动态人员是否被选中
             */
            function isDynamicItemSelected(dynamicId) {
                return $("ul.selectedDynamicList li input[value='" + dynamicId + "']", $dlgElem).length > 0;
            }

            /**
             * 取消动态人员选中
             */
            function removeSelectedDynamicItem(dynamicId) {
                $("ul.selectedDynamicList li input[value='" + dynamicId + "']", $dlgElem).parent().remove();
                $(".dynamic .aviableDynamicList li input[value='" + dynamicId + "']", $dlgElem).attr("checked", false);
            }

            /**
             * 生成动态人员选中的元素
             */
            function generateDynamicSelectedHtml(dynamicId, dynamicName) {
                var html = "";
                html += "<input type='hidden' value='" + dynamicId + "' data-dynamicName='" + dynamicName + "'/>";
                html += '<i class="layui-icon-ext layui-icon-ext-dynamic-user"></i>';
                html += "<span>" + dynamicName + "</span>";
                html += "<a href='javascript:;' class='close'>" +
                    "<i class='layui-icon layui-icon-close'></i>" +
                    "</a>";
                return "<li>" + html + "</li>";
            }

            /**
             * 获取角色列表
             */
            function getRoleList(offset, callback) {
                if (!cache.roles) {
                    cache.roles = {};
                }
                if (!cache.roles[offset]) {
                    $.post("/core/enterprise.user/departmentList?eid={$eid}", {
                        "offset": offset,
                        // 'size': 1
                    }, function (response) {
                        cache.roles[offset] = response.data;
                        callback(cache.roles[offset]);
                    });
                } else {
                    callback(cache.roles[offset]);
                }
            }

            /**
             * 获取部门列表
             *
             * @param parentDeptId
             * @param callback
             * @returns {*}
             */
            function getDeptList(parentDeptId, callback) {
                if (!cache.depts[parentDeptId]) {
                    $.post("/core/enterprise.user/departmentList?eid={$eid}", {"parentDepartmentId": parentDeptId}, function (response) {
                        cache.depts[parentDeptId] = response.data;
                        callback(cache.depts[parentDeptId]);
                    }, "json");
                } else {
                    callback(cache.depts[parentDeptId]);
                }
            }


            /**
             * 获取部门的用户列表
             *
             * @param deptId
             * @param offset
             * @param callback
             * @returns {*}
             */
            function getUserList(deptId, offset, callback) {
                if (!cache.users[deptId]) {
                    cache.users[deptId] = {};
                }
                if (!cache.users[deptId][offset]) {
                    $.post("/core/enterprise.user/userSimplelist?eid={$eid}", {
                        "departmentId": deptId,
                        'offset': offset,
                        // 'size': 1
                    }, function (response) {
                        cache.users[deptId][offset] = response.data;
                        callback(cache.users[deptId][offset]);
                    });
                } else {
                    callback(cache.users[deptId][offset]);
                }
            }
        });
    });
</script>